﻿using HtmlAgilityPack;
using Spider.Rules;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Spider.Analyse
{
    /// <summary>
    /// 分析 响应回来的信息
    /// </summary>
    public abstract class AnalyseBase
    {
        /// <summary>
        /// 子类实现 自己对应规则的实现
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="doc"></param>
        /// <param name="rule"></param>
        /// <returns></returns>
        public abstract List<T> GetListData<T>(HtmlDocument doc, IRule rule, object o = null)
             where T : class, new();

        ///// <summary>
        ///// 开始解析HTML页面
        ///// </summary>
        ///// <typeparam name="T">T 必须是引用类型并且 必须有默认构造函数</typeparam>
        ///// <param name="html">页面信息</param>
        ///// <param name="rule">规则信息</param>
        ///// <returns></returns>
        //public abstract T AnalyseStart<T>(string html, IRule rule)
        //    where T : class, new();
        public virtual List<T> AnalyseStart<T>(string html, IRule rule, object o = null)
            where T : class, new()
        {
            if (string.IsNullOrEmpty(html))
            {
                return new List<T>();
            }
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(html);
            var listEntity = GetListData<T>(doc, rule, o);
            return listEntity;
        }

        /// <summary>
        /// 解析HTML
        /// </summary>
        /// <param name="html"></param>
        /// <param name="rule"></param>
        /// <param name="o"></param>
        /// <returns></returns>
        public virtual string AnalyseHtml(string html, string rule, object o = null)
        {
            if (string.IsNullOrEmpty(html))
            {
                throw new Exception("html 不能为空");
            }
            string str = "";

            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(html);
            HtmlNode res = doc.DocumentNode.SelectSingleNode(rule);
            return AnalyseString(res, o);
        }

        /// <summary>
        /// 解析出想要的字符串信息
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        public virtual string AnalyseString(HtmlNode node, object o = null)
        {
            if (node == null)
            {
                throw new Exception("错误，请输入正确的HTML 节点");
            }
            return node.InnerHtml;
        }


    }
}
